package com.dian.diabetes.activity.report;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.dian.diabetes.R;
import com.dian.diabetes.activity.BasicActivity;
import com.dian.diabetes.activity.TranLoading;
import com.dian.diabetes.db.UserInfoBo;
import com.dian.diabetes.db.dao.UserInfo;
import com.dian.diabetes.drawer.activity.MainActivity;
import com.dian.diabetes.tool.Preference;
import com.dian.diabetes.utils.ContantsUtil;
import com.dian.diabetes.utils.DateUtil;
import com.dian.diabetes.utils.HttpServiceUtil;
import com.dian.diabetes.widget.anotation.ViewInject;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 
 * 查看每月综合报告
 * @author 小新
 * 
 */
public class UserReportActivityUpdate extends BasicActivity implements OnClickListener{
	
	@ViewInject(id = R.id.current_day)
	private TextView curMonth;
	@ViewInject(id = R.id.home)
	private ImageView homeBtn;
	@ViewInject(id = R.id.pre)
	private ImageButton preBtn;
	@ViewInject(id = R.id.next)
	private ImageButton nextBtn;
	
	@ViewInject(id = R.id.avatar_report)
	private ImageView avatar;
	@ViewInject(id = R.id.report_age)
	private TextView age;
	@ViewInject(id = R.id.report_weight)
	private TextView weight;
	@ViewInject(id = R.id.report_bmi)
	private TextView bmi;
	@ViewInject(id = R.id.report_height)
	private TextView height;
	@ViewInject(id = R.id.report_waistline)
	private TextView waistline;
	
	@ViewInject(id = R.id.report_result)
	private TextView result;
	
	@ViewInject(id = R.id.report_result_word)
	private LinearLayout result_word;
	@ViewInject(id = R.id.report_suggest_word)
	private TextView suggest_word;
	@ViewInject(id = R.id.report_sportsuggest_word)
	private TextView sportsuggest_word;
	@ViewInject(id = R.id.report_sugarsuggest_word)
	private TextView sugarsuggest_word;
	@ViewInject(id = R.id.id_flowlayout)
	private FlowLayout mFlowLayout;
	
	@ViewInject(id = R.id.report_nodata)
	private TextView tvData;
	@ViewInject(id = R.id.report_data)
	private LinearLayout lData;
	
	@ViewInject(id = R.id.report_suggest)
	private TextView suggest;
	@ViewInject(id = R.id.report_sportsuggest)
	private TextView sportsuggest;
	@ViewInject(id = R.id.report_sugarsuggest)
	private TextView sugarsuggest;
	@ViewInject(id = R.id.report_sportsuggest_layout)
	private LinearLayout sportsuggest_layout;
	@ViewInject(id = R.id.report_sugarsuggest_layout)
	private LinearLayout sugarsuggest_layout;
	
	@ViewInject(id = R.id.report_lab)
	private TextView lab;
	@ViewInject(id = R.id.report_lab_result)
	private TextView lab_word;
	@ViewInject(id = R.id.report_lab_layout)
	private LinearLayout lab_layout;
	
	@ViewInject(id = R.id.report_doctorinfo)
	private TextView doctor;
	@ViewInject(id = R.id.report_doctorinfo_word)
	private TextView doctor_word;
	@ViewInject(id = R.id.report_doctorinfo_layout)
	private LinearLayout doctor_layout;
	
	private final int NEXT = 1;
	private final int BEFORE = -1;
	private TranLoading loading;
	private boolean isLoading = false;
	private boolean doubletimes = false;
	
	private Long mid;
	private Date curentDate;
	private Handler handler;
	private UserInfoBo userInfoBo;
	private DecimalFormat format;
	private DisplayImageOptions options;
	public  ReturnReport allInfo = new ReturnReport();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_report_layout2);
		options = new DisplayImageOptions.Builder()
		.showStubImage(R.drawable.photo_default)
		.showImageForEmptyUri(R.drawable.photo_default)
		.showImageOnLoading(R.drawable.photo_default)
		.showImageOnFail(R.drawable.photo_default).cacheInMemory(true)
		.cacheOnDisc(true).build();
		format = new DecimalFormat("##0.0");
		userInfoBo = new UserInfoBo(context);
		curentDate = new Date();
		handler = new Handler();
		loading = new TranLoading(context);
		initActivity();
//		initTag();

		loadAvatar();
		loadData(0);
	}

    private void loadAvatar() {
    	mid = Preference.instance(context).getLong(ContantsUtil.USER_MID);
    	UserInfo uInfo = userInfoBo.getUinfoByMid(mid);
    	if(uInfo == null){
    		avatar.setImageResource(R.drawable.user_icon_unkown);
    	}else{
    		if(uInfo.getAvatar() != null) {
				ImageLoader.getInstance().displayImage(uInfo.getAvatar(), avatar,options);
			} else {
				avatar.setImageResource(R.drawable.photo_default);
			}
    	}
	}

//	private void initTag() {

//		LayoutInflater mInflater = LayoutInflater.from(this);

//		for (int i = 0; i < mVals.length; i++)

//		{

//			TextView tv = (TextView) mInflater.inflate(R.layout.tv,mFlowLayout, false);

//			tv.setText(mVals[i]);

//			mFlowLayout.addView(tv);

//		}

//	}


	private void initActivity() {
		homeBtn.setOnClickListener(this);
		preBtn.setOnClickListener(this);
		nextBtn.setOnClickListener(this);
		
		result.setOnClickListener(this);
	}

	
	
	@Override
	public void onClick(View view) {
		switch(view.getId()){
		case R.id.home:
			if(isLoading)
			return;
			Intent intent = new Intent(this,MainActivity.class);
			startActivity(intent);
//			finish();

			break;
		case R.id.pre:
			loadData(BEFORE);
			break;
		case R.id.next:
			loadData(NEXT);
			break;
		case R.id.report_result:
//			if(!doubletimes){

//				doubletimes = true;

//				LinearLayout.LayoutParams layoutParams = (LayoutParams) result_word.getLayoutParams();

//				layoutParams.height = LayoutParams.MATCH_PARENT;

//				result_word.setLayoutParams(layoutParams);

//			}else{

//				doubletimes = false;

//				LinearLayout.LayoutParams layoutParams = (LayoutParams) result_word.getLayoutParams();

//				layoutParams.height = 40;

//				result_word.setLayoutParams(layoutParams);

//			}

			break;
		default:break;
		}
	}

	private void loadData(int sub) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(curentDate);
		calendar.add(Calendar.MONTH, sub);		//通过设置来加减月份

		curentDate = calendar.getTime();
		String today = DateUtil.parseToDate(System.currentTimeMillis());
		String temp = DateUtil.parseToDate(curentDate.getTime());
		if (today.equals(temp)) {
//			nextBtn.setClickable(false);

			nextBtn.setVisibility(View.INVISIBLE);
		} else {
//			nextBtn.setClickable(true);

			nextBtn.setVisibility(View.VISIBLE);
		}
		curMonth.setText(DateUtil.parseToString(curentDate, DateUtil.yyyyMM));
		notifyData();
	}
	
	private void notifyData(){
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("sex", ContantsUtil.curInfo.getSex());
		params.put("mid", ContantsUtil.DEFAULT_TEMP_UID);
		params.put("date", DateUtil.parseToInt(curentDate.getTime()));
		isLoading = true;
		loading.show();
		loading.hideLabel();
		HttpServiceUtil.request(ContantsUtil.GET_RESULT1, "post", params, new httpCallBack());
	}
	/**
	 * http请求的回调函数
	 * @author 小新
	 *
	 */
	public class httpCallBack implements HttpServiceUtil.CallBack{

		@Override
		public void callback(String json) {
			try {
				if(json != null){
					loading.dismiss();
					isLoading = false;
					String allData = new JSONObject(json).optString("data");
					Log.e(" JSON allData : ", allData);
					if((allData != null) && (allData.length() > 0)){
						tvData.setVisibility(View.GONE);
						lData.setVisibility(View.VISIBLE);
						allInfo = new Gson().fromJson(allData, ReturnReport.class);
						handlemessage(allInfo);
					}else{
						tvData.setVisibility(View.VISIBLE);
						lData.setVisibility(View.GONE);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				loading.dismiss();
				isLoading = false;
				Toast.makeText(context, "获取数据失败",Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	private String testJson() {
		String TestData="";
		UserInfo2 userInfo = new UserInfo2("11", "11", "11", 11f, "11");
		Item sport = new Item("123", "456\n");
		Item suggest = new Item("123", "456\n");
		List<Item> items = new ArrayList<Item>();
		items.add(sport);
		items.add(suggest);
		Result result = new Result(items);
		Data dataTest = new Data(userInfo, result, suggest, sport);
		TestData = new Gson().toJson(dataTest);
		return TestData;
	}
	
	private void handlemessage(final ReturnReport allInfo2) {
		handler.post(new Runnable() {
			
			@Override
			public void run() {
				String[] tags = new String[allInfo2.getDataSymptom().size()];
				if(allInfo2 != null){
					for(Item item : allInfo2.getItems()){
						if((item.getName() != null) && (item.getName().contains("综合建议"))){
							suggest.setText(item.getName());
							suggest_word.setText(item.getValue());
						}
						if((item.getName() != null) && (item.getName().contains("运动饮食建议"))){
							if(!item.getValue().equals("")){
								sportsuggest_layout.setVisibility(View.VISIBLE);
								sportsuggest.setText(item.getName());
								sportsuggest_word.setText(item.getValue());
							}else{
								sportsuggest_layout.setVisibility(View.GONE);
							}
							
						}
						if((item.getName() != null) && (item.getName().contains("控糖建议"))){
							if(!item.getValue().equals("")){
								sugarsuggest_layout.setVisibility(View.VISIBLE);
								sugarsuggest.setText(item.getName());
								sugarsuggest_word.setText(item.getValue());
							}else{
								sugarsuggest_layout.setVisibility(View.GONE);
							}
						}
						if((item.getName() != null) && (item.getName().contains("实验室异常指标"))){
							if(!item.getValue().equals("")){
								lab_layout.setVisibility(View.VISIBLE);
								lab.setText(item.getName());
								lab_word.setText(item.getValue());
							}else{
								lab_layout.setVisibility(View.GONE);
							}
						}
					}
					if(allInfo2.doctorInfo != null){
						doctor_word.setText("医生姓名  : "+allInfo2.doctorInfo.getDoctorName()+"\n"+"手机号码  : "+ allInfo2.doctorInfo.getDoctorPhone());
					}else{
						doctor_word.setText("您还未签约医生。。。");
					}
					for(int i=0;i<allInfo2.getDataSymptom().size();i++)
					tags[i] = allInfo2.getDataSymptom().get(i).getSymptom_name();
					updateResult(tags);
					initBaseInfo(allInfo2.getUserInfo());
					if(allInfo2.getResult().getResultItems() != null){
						result_word.removeAllViews();
						for(int i=0;i<allInfo2.getResult().getResultItems().size();i++){
							TextView textView = new TextView(context);
							textView.setText(allInfo2.getResult().getResultItems().get(i).getValue());
							textView.setBackgroundColor(Color.parseColor("#ffffed"));
							LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
							layoutParams.setMargins(dip2px(15), dip2px(5), dip2px(15), dip2px(15));
							textView.setLayoutParams(layoutParams);
							result_word.addView(textView);
						}
					}else{
						result_word.removeAllViews();
					}
				}
			}
		});
	}
	/**
	 * dp\px转换函数
	 * @param dpValue
	 * @return
	 */
	public int dip2px(float dpValue) {  
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (dpValue * scale + 0.5f);  
    }  
	/**
	 * 更新标签值
	 * @param tags
	 */
	private void updateResult(String[] tags){
		LayoutInflater mInflater = LayoutInflater.from(this);
		mFlowLayout.removeAllViews();
		for (int i = 0; i < tags.length; i++)
		{
			TextView tv = (TextView) mInflater.inflate(R.layout.tv,mFlowLayout, false);
			tv.setText(tags[i]);
			mFlowLayout.addView(tv);
		}
	}
	/**
	 * 更新个人信息
	 * @param userInfo
	 */
	private void initBaseInfo(UserInfo2 userInfo) {
		age.setText(getString(R.string.report_age) + userInfo.getAge());
		weight.setText(getString(R.string.report_weight) + userInfo.getWeight());
		bmi.setText(getString(R.string.report_bmi) + format.format(userInfo.getBmi()));
		height.setText(getString(R.string.report_height) + userInfo.getHeight());
		waistline.setText(getString(R.string.report_waistline) + userInfo.getWaistline());
	}
	
}